package com.zsjt.yysapi.common.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import com.zsjt.yysapi.common.config.TencentApiSmsConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 验证码工具类
 */
@Component
public class CaptchaUtil {

    @Autowired
    private TencentApiSmsConfig tencentApiSmsConfig;

    /**
     * 腾讯云短信验证码
     *
     * @return
     */
    public boolean tencentSendSms(String phone, String code) throws TencentCloudSDKException {

        Credential cred = new Credential(tencentApiSmsConfig.getSecretId(), tencentApiSmsConfig.getSecretKey());

        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("sms.tencentcloudapi.com");

        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);

        SmsClient client = new SmsClient(cred, "", clientProfile);

        SendSmsRequest req = new SendSmsRequest();
        String[] phoneNumberSet1 = {"+86" + phone};
        req.setPhoneNumberSet(phoneNumberSet1);

        req.setTemplateID(tencentApiSmsConfig.getTemplateID());
        req.setSign(tencentApiSmsConfig.getSign());

        String[] templateParamSet1 = {code, tencentApiSmsConfig.getExpireTime()};
        req.setTemplateParamSet(templateParamSet1);

        req.setSmsSdkAppid(tencentApiSmsConfig.getSdkAppId());

        SendSmsResponse resp = client.SendSms(req);

        JSONObject jsonObject = JSONObject.parseObject(SendSmsResponse.toJsonString(resp));
        JSONArray sendStatusSet = jsonObject.getJSONArray("SendStatusSet");
        if (sendStatusSet.size() > 0) {
            Map<String, Object> map = (Map<String, Object>) sendStatusSet.get(0);
            String c = (String) map.get("Code");
            if ("Ok".equals(c)) {
                return true;
            }
        }
        return false;
    }
}
